import React, { useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { AtModal } from 'taro-ui'
import {Image, View, Swiper,SwiperItem, Text} from '@tarojs/components'
import "taro-ui/dist/style/components/modal.scss";
import {getParames} from '@/utils/index'
import './index.scss'

export default function Home(props) {
  let buttonStatus = {
    pre_sale:'预售',
    favorites:'想看',
    already_favorites:'已想看',
    sale:'购票'
  }
  let capsule = {}
  if(process.env.TARO_ENV === 'weapp') capsule = Taro.getMenuButtonBoundingClientRect()
  const [showModal,setShowModal] = useState(false)
  const [cinemaInfo,setCinemaInfo] = useState({})
  const [hotFilm,setHotFilm] = useState([])
  const [banner,setBanner] = useState([])
  const [welfareList,setWelfareList] = useState([])
  const [adList,setAdList] = useState([])
  const [comingSoon,setComingSoon] = useState([])
  
  useEffect(()=>{
    Taro.$get('/news/news/advertisingPosition/selectAdvertisingListByAlias/cinema_top').then(res=>{
      if(res.code == '1') setBanner(res.content?.advertisesList)
    })
    Taro.$get('/news/news/advertisingPosition/selectAdvertisingListByAlias/cinema_center').then(res=>{
      if(res.code == '1') setWelfareList(res.content?.advertisesList)
    })
    Taro.$get('/news/news/advertisingPosition/selectAdvertisingListByAlias/cinema_bottom').then(res=>{
      if(res.code == '1') setAdList(res.content?.advertisesList)
    })
    if(Taro.getStorageSync('merchantId')){
      setCinemaInfo(Taro.getStorageSync('selectMerchant'))
      _initData(Taro.getStorageSync('merchantId'))
    }
    Taro.eventCenter.on('updateMerchant',e=>{
      setCinemaInfo(Taro.getStorageSync('selectMerchant'))
      _initData(Taro.getStorageSync('merchantId'))
    })
  },[])
  useDidShow(()=>{
    if(!Taro.getStorageSync('merchantId')){
      Taro.reLaunch({
        url:'/mainPages/select-cinema/index'
      })
      return;
    }
  })
  const handleBannerJump =url=>{
    if(url?.includes('openmini')){
      let appId = ''
      if(process.env.TARO_ENV === 'weapp') appId = getParames(url).wxAppId
      Taro.navigateToMiniProgram({
        appId
      })
      return;
    }
    if(url?.includes('https://')){
      url = `/pages/fineEngine/webView?url=${encodeURIComponent(url)}`
    }
    Taro.navigateTo({
      url
    })
  }
  const handleButton = res=>{  ///  点击购票,预售,想要按钮
    if(res.buttonStatus == 'sale'){
      Taro.verifyLogin()
      Taro.navigateTo({
        url:`/mainPages/plan/index?id=${res.id}`
      })
    }
    if(res.buttonStatus == 'pre_sale'){
      Taro.verifyLogin()
    }
    if(res.buttonStatus == 'favorites' || res.buttonStatus == 'already_favorites'){
      if(res.isLike){
        Taro.$del('/social/topicLike/v1',{appId:Taro.$mpAppid,topicId:res.id}).then(ret=>{
          if(ret.code == '1'){
            res.isLike = false
            setComingSoon((pre)=>{
              return pre.slice()
            })
          }
        })
        return;
      }
      Taro.$post('/social/topicLike',{appId:Taro.$mpAppid,topicId:res.id}).then(ret=>{
        if(ret.code == '1'){
          res.isLike = true
          setComingSoon((pre)=>{
            return pre.slice()
          })
        }
      })
    }
  }
  const _initData = cinemaId=>{
    Taro.$get('/cinema-app/api/v1/film/hotFilm',{cinemaId}).then(res=>{
      if(res.code == '1') setHotFilm(res.content)
    })
    Taro.$get('/cinema-app/api/v1/film/comingSoon',{cinemaId}).then(res=>{
      if(res.code == '1'){
        let arr = [],topicIds = []
        res.content?.map(res=>{
          res.filmList.map(ret=>{arr.push(ret)})
        })
        setComingSoon(arr)
        arr.map(ret=>{
          if(ret.buttonStatus == 'favorites') topicIds.push(ret.id)
        })
        Taro.$post('/social/topicLike/isLikeByTopicIds',{appId:Taro.$mpAppid,topicIds}).then(res=>{
          if(res.code == '1' && res.content?.length){
            res.content.map(ret=>{
              arr.map(result=>{
                if(result.id == ret.topicId){
                  result.isLike = ret.isLike
                }
              })
            })
            setComingSoon((pre)=>{
              return arr.slice()
            })
          }
        })
      }
    })
  }
  return (
    <View className='home'>
      <View className="home-nav-bar" style={{paddingTop:capsule.top+'PX'}}>
        <View className="box-flex" style={{lineHeight:capsule.height+'PX'}} onClick={()=>{
          Taro.navigateTo({
            url:'/mainPages/select-cinema/index'
          })
        }}>
          <Image src={require('@/images/common/location.svg')} mode='widthFix' style={{width:20,height:20}} />
          {cinemaInfo.cinemaNickName}
          <Text className='at-icon at-icon-chevron-down' style={{marginLeft:4}}></Text>
        </View>
      </View>

      <View className="home-main">
        {banner?.length?
          <Swiper className='main-swiper' autoplay>
            {banner.map(res=>{
              return <SwiperItem key={res.id} onClick={()=>{handleBannerJump(res.url)}}>
                <Image lazyLoad className='swiper-img' src={res.imageUrl} mode='aspectFill' />
              </SwiperItem>
            })}
          </Swiper>
        :null}

        <View className="main-goods">
          <View className="goods-title">
            <Text className='title-h2'>热映影片</Text>
            <View onClick={()=>{
              Taro.reLaunch({
                url:'/pages/movie/index?tabs=0'
              })
            }}>
              全部 <Text className='at-icon at-icon-chevron-right'></Text>
            </View>
          </View>
          {hotFilm?.length?
          <View className="goods-list not-bar">
            {hotFilm.map(res=>{
              return <View className="list-item" key={res.id}>
                <View className="item-img" onClick={()=>{
                  Taro.navigateTo({
                    url:`/mainPages/video-detail/index?id=${res.id}`
                  })
                }}>
                  {res.filmTip?
                  <View className='img-icon'>
                    {res.filmTip.map(res=>{
                      return <View key={res}>{res}</View>
                    })}
                  </View>:null}
                  <Image className='img' lazyLoad src={!res.filmPosterUrl?.includes('alicdn')?res.filmPosterUrl:res.filmPosterUrl+'_240x240'} />
                  {res.score?<View className="img-footer"><Text style={{fontWeight:600,fontSize:'12px'}}>{res.score}</Text> 分</View>:null}
                </View>
                <View className="item-h2 dot">{res.filmNickName}</View>
                <View className="item-span dot">{res.filmType || <Text>&nbsp;</Text>}</View>
                <View className={`item-button ${res.buttonStatus}`} onClick={()=>{
                  handleButton(res)
                }}>{buttonStatus[res.buttonStatus]}</View>
              </View>
            })}
          </View>:<View className='var-empty'>暂无数据</View>}
        </View>

        {welfareList?.length?
          <Swiper className='main-banner' style={{height:'50px'}} autoplay>
            {welfareList.map(res=>{
              return <SwiperItem key={res.id} onClick={()=>{handleBannerJump(res.url)}}>
                <Image lazyLoad src={res.imageUrl} style={{width:'100%',height:'50px'}} mode='widthFix' />
              </SwiperItem>
            })}
          </Swiper>
        :null}

        <View className="main-goods">
          <View className="goods-title">
            <Text className='title-h2'>即将上映</Text>
            <View onClick={()=>{
              Taro.reLaunch({
                url:'/pages/movie/index?tabs=1'
              })
            }}>
              全部 <Text className='at-icon at-icon-chevron-right'></Text>
            </View>
          </View>
          {comingSoon?.length?
          <View className="goods-list not-bar">
            {
            comingSoon.map(res=>{
              return <View className="list-item" key={res.id}>
                <View className="item-img" onClick={()=>{
                  Taro.navigateTo({
                    url:`/mainPages/video-detail/index?id=${res.id}`
                  })
                }}>
                  {res.filmTip?
                  <View className='img-icon'>
                    {res.filmTip.map(res=>{
                      return <View key={res}>{res}</View>
                    })}
                  </View>:null}
                  <Image className='img' lazyLoad src={!res.filmPosterUrl?.includes('alicdn')?res.filmPosterUrl:res.filmPosterUrl+'_240x240'} />
                  {res.score?<View className="img-footer"><Text style={{fontWeight:600,fontSize:'12px'}}>{res.score}</Text> 分</View>:null}
                </View>
                <View className="item-h2 dot">{res.filmNickName}</View>
                <View className="item-span dot">{res.filmType || <Text>&nbsp;</Text>}</View>
                <View className={`item-button ${res.buttonStatus == 'favorites'?res.isLike?'already_favorites':'favorites':res.buttonStatus}`} onClick={()=>{
                  handleButton(res)
                }}>{res.buttonStatus=='favorites'?res.isLike?'已想看':'想看':buttonStatus[res.buttonStatus]}</View>
              </View>
            })}
          </View>:<View className='var-empty'>暂无数据</View>}
        </View>

        {adList?.length?
          <Swiper className='main-banner' autoplay>
            {adList.map(res=>{
              return <SwiperItem key={res.id} onClick={()=>{handleBannerJump(res.url)}}>
                <Image lazyLoad src={res.imageUrl} className='banner-img' mode='aspectFill' />
              </SwiperItem>
            })}
          </Swiper>
        :null}

        {/* <View className="main-list">
          <View className="list-title">上影甄选</View>
          <View className="list-item">
            <Image lazyLoad src='https://img1.baidu.com/it/u=3486651663,3991438881&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500' className='item-img' mode='aspectFill' />
            <View style={{padding:'10px 8px'}}>
            <View className="item-h2 dot2">美影正版 阿凡提的故事 阿凡提和毛驴Q版手办...</View>
            <View className="item-info">
              <View className="info-price"><Text style={{fontSize:12}}>￥</Text>25.90</View>
              <View className="info-span">已售 200 件</View>
            </View>
            </View>
          </View>
        </View> */}
      </View>

      <AtModal isOpened={showModal}>
        <View className="home-modal">
          <Image className='modal-img' lazyLoad src='https://img1.baidu.com/it/u=3486651663,3991438881&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500' mode='widthFix'></Image>
          <View className="at-icon at-icon-close-circle" onClick={()=>{setShowModal(false)}}></View>
        </View>
      </AtModal>
    </View>
  )
}
